<?php

namespace app\common\model;

use think\Env;
use think\Model;
use think\Session;
use traits\model\SoftDelete;

class Shop extends Model
{

    use SoftDelete;

    protected $deleteTime = 'deletetime';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [

    ];

    const STATUS_OK = 1;
    const STATUS_CLOSE = 0;
    static $statusMap = [
        self::STATUS_OK => '开启',
        self::STATUS_CLOSE => '关闭',
    ];

    const SOURCE_PLATFORM = 1;
    const STATUS_OFFLINE = 2;
    static $sourceMap = [
        self::SOURCE_PLATFORM => '平台分配',
        self::STATUS_OFFLINE => '线下发展',
    ];

    public function amapProvince()
    {
        return $this->belongsTo('amap', 'province', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function amapCity()
    {
        return $this->belongsTo('amap', 'city', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function amapDistricts()
    {
        return $this->belongsTo('amap', 'districts', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function shopImages()
    {
        return $this->hasMany(Images::class, 'shop_id');
    }


    public function shopGoods()
    {
        return $this->hasMany(ShopGoods::class, 'shop_id')->where('status', ShopGoods::STATUS_OK);
    }

    public function comment()
    {
        return $this->hasMany('orderComment', 'shop_id');
    }

    public function agent()
    {
        return $this->belongsTo('Agent', 'agent_id', 'id', [], 'LEFT')->setEagerlyType(0);
//        return $this->belongsTo(Agent::class);
    }


    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['logintime']) ? $data['logintime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function setLogoAttr($value)
    {
        if (!empty($value)){
            $arr = parse_url($value);
            return $arr['path'];
        }
        return '';
    }

    public function getLogoAttr($value, $data)
    {
        return $value ? Env::get('app.app_host').$value : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    public static function getShopForLock($shop_id)
    {
        return self::where('id', $shop_id)->where('status', self::STATUS_OK)->lock(true)->find();
    }


}
